import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from imutils.face_utils import FaceAligner
from imutils.face_utils import rect_to_bb
import imutils
import dlib


# 解决中文显示问题
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False

path='Pic/source.jpg'
source = cv.imread(path)
img = cv.cvtColor(source,cv.COLOR_RGB2GRAY)

img_big_1=cv.resize(img,None,fx=2,fy=2,interpolation=cv.INTER_CUBIC)
img_big_2=cv.resize(img,None,fx=2,fy=2,interpolation=cv.INTER_LINEAR)
img_big_3=cv.resize(img,None,fx=2,fy=2,interpolation=cv.INTER_NEAREST)
img_small_1=cv.resize(img,None,fx=0.5,fy=0.5,interpolation=cv.INTER_CUBIC)
img_small_2=cv.resize(img,None,fx=0.5,fy=0.5,interpolation=cv.INTER_LINEAR)
img_small_3=cv.resize(img,None,fx=0.5,fy=0.5,interpolation=cv.INTER_NEAREST)

cv.imwrite('Pic/CUBIC_big.png',img_big_1)
cv.imwrite('Pic/LINEAR_big.png',img_big_1)
cv.imwrite('Pic/NEAREST_big.png',img_big_3)
cv.imwrite('Pic/CUBIC_small.png',img_small_1)
cv.imwrite('Pic/LINEAR_small.png',img_small_2)
cv.imwrite('Pic/NEAREST_small.png',img_small_3)

cv.imshow("CUBIC_big",img_big_1)
cv.imshow("LINEAR_big",img_big_2)
cv.imshow("NEAREST_big",img_big_3)
cv.waitKey(0)

# 第二题
column,row=img.shape

pts1 = np.float32([[0, 0], [row - 1, 0], [0, column - 1]])  #原图
pts2 = np.float32([[row - 1, 0], [0, 0], [row-1, column - 1]])  #水平对称
pts3 = np.float32([[400, 0], [row +399, 0], [400, column - 1]])    #平移变换400个单位
pts4 = np.float32([[0, 400], [row-1, 400], [0, column +399]])    #垂直偏移变换

M = cv.getAffineTransform(pts1, pts1)
M1 = cv.getAffineTransform(pts1, pts2)
M2 = cv.getAffineTransform(pts1, pts3)
M3 = cv.getAffineTransform(pts1, pts4)

dst = cv.warpAffine(img, M, (row+400,column+400))
dst1 = cv.warpAffine(img, M1, (row+400,column+400))
dst2 = cv.warpAffine(img, M2, (row+400,column+400))
dst3 = cv.warpAffine(img, M3, (row+400,column+400))

cv.imwrite("Pic\yuantu.png",dst)
cv.imwrite("Pic\duichen.png",dst1)
cv.imwrite("Pic\pinyi.png",dst2)
cv.imwrite("Pic\chuizhi.png",dst3)

cv.waitKey(1000)
cv.destroyAllWindows()

# 第三题

def face_align(img_path):
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor("model/shape_predictor_68_face_landmarks.dat")
    # 初始化 FaceAligner 类对象
    fa = FaceAligner(predictor, desiredFaceWidth=256)
    image = cv.imread(img_path)
    image = imutils.resize(image, width=600)
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    cv.imshow("Input", image)

    rects = detector(gray, 2)

    for rect in rects:
        (x, y, w, h) = rect_to_bb(rect)
        face_orig = imutils.resize(image[y:y + h, x:x + w], width=256)
        # 调用 align 函数对图像中的指定人脸进行处理
        face_aligned = fa.align(image, gray, rect)
        cv.imshow("Original", face_orig)
        cv.imshow("Aligned", face_aligned)
        cv.waitKey(0)
        cv.destroyAllWindows()
        cv.imwrite("Pic/face_aligned.png",face_aligned)
        cv.imwrite("Pic/face_orig.png", face_orig)
        return

face_align('Pic/face00.jpg')
